﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using umbraco.cms.businesslogic.datatype;
using System.Xml;
using System.Web.Script.Serialization;

namespace MT.Flag.Umbraco.DataTypes.TabularData
{
    public class TabularDataData : DefaultData
    {
        public TabularDataData(BaseDataType dataType) : base(dataType) { }

        /// <summary>
        /// Converts the data value to XML.
        /// </summary>
        /// <param name="data">The data to convert to XML.</param>
        /// <returns></returns>
        public override XmlNode ToXMl(XmlDocument data)
        {
            // check that the value isn't null and starts with an opening angle-bracket.
            if (this.Value != null && !string.IsNullOrEmpty(this.Value.ToString()) && this.Value.ToString().StartsWith("<"))
            {
                // load the value into an XML document.
                XmlDocument xd = new XmlDocument();
                xd.LoadXml(this.Value.ToString());

                // return the XML node.
                return data.ImportNode(xd.DocumentElement, true);
            }

            // if the value is null or empty, create a <Data> XML document, and use that
            if (this.Value == null || string.IsNullOrEmpty(this.Value.ToString()))
            {
                XmlDocument xd2 = new XmlDocument();
                xd2.LoadXml("<Data/>");

                // return the XML node
                return data.ImportNode(xd2.DocumentElement, true);
            }

            // otherwise render the value as default (in CDATA)
            return base.ToXMl(data);
        }




    }
}
